package cn.dq.demo.controller;

import cn.dq.demo.DemoApplication;
import cn.dq.demo.design.singleton.LazySingletonDesign;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Properties;

@RestController
public class HelloController {

    @RequestMapping(value = "/singleton")
    public String testSingleton(@RequestParam(value = "test1", required = false) String test) {
        LazySingletonDesign lazySingletonDesign = LazySingletonDesign.getSingleInstance("test");
        return lazySingletonDesign.getName();
    }

    @RequestMapping(value = "/recoursePro")
    public String testRecourseProperty() throws IOException {
        InputStream inputStream = HelloController.class.getClassLoader().getResourceAsStream("application.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        return properties.getProperty("server.servlet.context-path");
    }

    @RequestMapping(value = "/reflection")
    public String testReflection() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        DemoApplication demoApplication = (DemoApplication) Class.forName("cn.dq.demo.DemoApplication").newInstance();
        Method[] methods = demoApplication.getClass().getDeclaredMethods();
        String methodName = methods.length == 0 ? null : methods[0].getName();
        return methodName;
    }

    @RequestMapping(value = "/applicationContext")
    public String testApplicationContext() {
        //error javax.management.InstanceAlreadyExistsException
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        return applicationContext.getBean("testBean").toString();
    }
}
